package cn.tannn.captcha.sdk.config;

import cn.tannn.captcha.sdk.dict.CacheMode;
import cn.tannn.captcha.sdk.exception.CaptChaException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Objects;

/**
 * 验证码配置文件
 *
 * @author tnnn
 * @version V1.0
 * @date 2023-02-27 15:34
 */
@Component
@ConfigurationProperties(prefix = "captcha")
public class CaptchaSetting {
    private static final Logger LOG = LoggerFactory.getLogger(CaptchaSetting.class);

    /**
     * 滑动验证码的资源图集，随机不同的图片(本地图集)
     * <p> 本地: "E:\\测试图片\\" (文件夹下不允许再有文件夹)
     * <p> 本地图集 里面有多张图会随机抽取
     * <p> 默认: 内置的一张图
     */
    String slide;

    /**
     * 过期时间/秒
     * <p>项目里自己实现，我在server里用的</p>
     * 默认  1分钟
     */
    private Long expireTime;

    /**
     * 验证码存储前缀-区分不同项目用的
     * <p>项目里自己实现，我在server里用的</p>
     */
    private String prefix;


    /**
     * 缓存模式
     * <p>项目里自己实现，我在server里用的</p>
     * <p>默认redis</p>
     * @see CacheMode
     */
    private CacheMode cache;


    /**
     * 验证码字体配置
     */
    @NestedConfigurationProperty
    private CaptchaFontConfig font = new CaptchaFontConfig();


    @Override
    public String toString() {
        return "CaptchaSetting{" +
                "slide='" + slide + '\'' +
                ", expireTime=" + expireTime +
                ", prefix='" + prefix + '\'' +
                ", cache=" + cache +
                ", font=" + font +
                '}';
    }

    public String getSlide() {
        return slide;
    }

    public void setSlide(String slide) {
        this.slide = slide;
    }

    public String getPrefix() {
        return prefix==null ? "captcha" : prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public Long getExpireTime() {
        return expireTime==null?60L:expireTime;
    }

    public void setExpireTime(Long expireTime) {
        this.expireTime = expireTime;
    }

    public CacheMode getCache() {
        return cache==null?CacheMode.REDIS:cache;
    }

    public void setCache(CacheMode cache) {
        this.cache = cache;
    }

    public BufferedImage sildeFile(){

        try {
            if(Objects.isNull(slide)){
                return getDefaultBufferedImage();
            }else {
                File file = new File(slide);
                if(!file.exists()){
                    return getDefaultBufferedImage();
                }
                if(file.isDirectory()){
                    File[] files = file.listFiles();
                    if(Objects.isNull(files)){
                        return getDefaultBufferedImage();
                    }else {
                        //创建随机对象
                        SecureRandom random = new SecureRandom();
                        //随机数组索引，nextInt(len-1)表示随机整数[0,(len-1)]之间的值
                        int arrIdx = random.nextInt(files.length-1);
                        file = files[arrIdx];
                    }

                }
                return ImageIO.read(file);
            }

        } catch (Exception e) {
            LOG.error("获取拼图资源失败");
            throw new CaptChaException("请设置正确的滑动资源图集",e);
        }
    }

    /**
     * 获取默认图片
     * @return BufferedImage
     * @throws IOException IOException
     */
    private static BufferedImage getDefaultBufferedImage() throws IOException {
        String defaultImages = "img/slide/test-2.png";
        ClassPathResource classpathResource = new ClassPathResource(defaultImages);
        return ImageIO.read(classpathResource.getInputStream());
    }


    public CaptchaFontConfig getFont() {
        return font;
    }

    public void setFont(CaptchaFontConfig font) {
        this.font = font;
    }
}
